package com.zl.smartmall.library.listener;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.zl.smartmall.library.util.CrashHandler;

/**
 * 获取微信用户信息数据监听器
 * @author 陈希然
 *
 */
public abstract class WechatUserinfoListener extends BaseListener {

	private static final String TAG = WechatUserinfoListener.class.getSimpleName();
	private String accessToken;
	
	/**
	 * @param accessToken 微信接口调用凭证
	 */
	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}
	
	@Override
	public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
		try {
			CrashHandler.d(TAG, response.toString());
			if(response.has("errcode")) {
				onResponseFailed();
				
			}else {
				int sex = response.getInt("sex");
				String openId = response.getString("openid");
				String nickname = response.getString("nickname");
				String province = response.getString("province");
				String city = response.getString("city");
				String country = response.getString("country");
				String headImgUrl = response.getString("headimgurl");
				String unionid = response.getString("unionid");

				onResponseSuccess(sex, nickname, province, city, country, headImgUrl, openId, unionid, accessToken);
			}
			
		} catch (JSONException e) {
			CrashHandler.e(e);
			onResponseFailed();
		}
	}
	
	@Override
	public void onFailure(int statusCode, Header[] headers,
			Throwable throwable, JSONObject errorResponse) {
		// TODO Auto-generated method stub
		CrashHandler.e(throwable);
		onResponseFailed();
	}
	
	@Override
	public void onNoMoreData() {}
	
	@Override
	public void onOffline() {}

	/**
	 * 获取微信用户信息成功回调
	 * @param sex 性别
	 * @param nickname 昵称
	 * @param province 省
	 * @param city 市
	 * @param country 国家
	 * @param headImgUrl 头像
	 * @param openId 授权用户唯一标识
	 * @param unionid 只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段
	 * @param accessToken 微信接口调用凭证
	 */
	public abstract void onResponseSuccess(int sex, String nickname, String province, String city, String country, String headImgUrl, String openId, String unionid, String accessToken);
}
